#ifndef __BOOKORDER_H_
#define __BOOKORDER_H_

#include <iomanip>
#include <fstream>
#include <iostream>
#include <list>
#include <vector>
#include <numeric>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEL(x) {if(x) { delete (x); (x) = NULL; }}
#define NAME_MAX_LEN	256

typedef enum {
	B_ORDER = 0,
	B_NAME, 
	B_AUTHOR,
}BOOK_ATTR;

class BookOrder {
public:
	BookOrder(){ order = 0; name = NULL; author = NULL; };
	BookOrder(int iNum, const char* iName, const char* iAuthor = NULL){  
		order = iNum;
		int iLen = strnlen(iName, NAME_MAX_LEN - 1);
		name = new char[NAME_MAX_LEN];
		memset(name, 0x00, NAME_MAX_LEN);
		memcpy(name, iName, iLen);
		if (iAuthor) {
			iLen = strnlen(iAuthor, NAME_MAX_LEN - 1);
			name = new char[NAME_MAX_LEN];
			memset(name, 0x00, NAME_MAX_LEN);
			memcpy(name, iAuthor, iLen);
		}
	};
	~BookOrder() { DEL(name); DEL(author); };

	int setOrder(int iOrder) { order = iOrder; return order;}
	int getOrder() { return order;}

	int setVal(const char* iStr, BOOK_ATTR type) {
		int iLen = strnlen(iStr, NAME_MAX_LEN - 1);
		switch (type) {
			case B_NAME:
				if (name) { DEL(name); }
				name = new char[NAME_MAX_LEN];
				memset(name, 0x00, NAME_MAX_LEN);
				memcpy(name, iStr, iLen);
				break;
			case B_AUTHOR:
				if (author) { DEL(author); }
				author = new char[NAME_MAX_LEN];
				memset(author, 0x00, NAME_MAX_LEN);
				memcpy(author, iStr, iLen);
				break;
			default:
				return -1;
				break;
		}
		return 0;
	};
	const char* getVal(BOOK_ATTR type) {
		switch (type) {
			case B_NAME:
				if (name) { return name; }
				break;
			case B_AUTHOR:
				if (author) { return author; }
				break;
			default:
				break;
		}
		return NULL;
	};

	bool operator < (BookOrder & b) {
		return order < b.getOrder();
	};

	bool operator == (BookOrder & b) {
		return (order == b.getOrder()) ? true : false;
	};

private:
	int order;
	char* name;
	char* author;
};

//typedef std::vector<BookOrder> BO;
typedef std::list<BookOrder> BO;
#define DBFILE "./db.txt"

class OrderManager {
public:
	OrderManager(){ orders.clear(); };
	~OrderManager() { orders.clear(); };

	int getOrderNum ();
	int addOrder(int iNum, const char* iName = NULL, const char* iAuthor = NULL);
	int delOrder(int iOrder);

	void priOrders();
	void sortOrders() {
		orders.sort();
	};
	void uniqueOrders() {
		orders.unique();
	};

	void saveToDB(const char* path);
	void readFromDB();

private:
	BO orders;
};

#endif
